define([], function () {
    var run_script = Config.knowbase.run_script || 0;
var preview = Config.knowbase.preview || 0;
var upload_max_size = Config.knowbase.upload_max_size || 10485760;
var editor_theme = Config.knowbase.editor_theme || 'classic';
var content_theme = Config.knowbase.content_theme || 'light';
var code_theme = Config.knowbase.code_theme || 'github';
var code_show_number = Config.knowbase.code_show_number || 0;
var height = Config.knowbase.height || window.innerHeight - 20;
var outline = Config.knowbase.outline || 0;
var mode = Config.knowbase.mode || 'wysiwyg';
var filter_tags = Config.knowbase.filter_tags || 1;
var auto_upload_image_from_text = Config.knowbase.auto_upload_image_from_text || 0;
var show_history = Config.knowbase.show_history || 0;
var show_link = Config.knowbase.show_link || 0;
var editor_id = null;
var params  = null;
// 修复flowchart恶心的define问题
window.forceLoad = true;
window.changeContent = false;
window.hasOldContent = false;
if (run_script == 1) {
  require.config({
    paths: {
      'vditor': '../addons/knowbase/js/index.min',
      'katex': '../addons/knowbase/dist/js/katex/katex.min',
      'echarts': '../addons/knowbase/dist/js/echarts/echarts.min',
      'mermaid': '../addons/knowbase/dist/js/mermaid/mermaid.min',
      'graphviz': '../addons/knowbase/dist/js/graphviz/full.render',
      'viz': '../addons/knowbase/dist/js/graphviz/viz',
      'lute': '../addons/knowbase/dist/js/lute/lute.min',
      'flowchart': '../addons/knowbase/dist/js/flowchart.js/flowchart.min',
      'plantuml': '../addons/knowbase/dist/js/plantuml/plantuml-encoder.min',
    },
    shim: {
      'vditor': {
        deps: [
          'plantuml',
          'viz',
          'graphviz',
          'mermaid',
          'echarts',
          'katex',
          'css!../addons/knowbase/css/index.css',
          'css!../addons/knowbase/css/common.css',
        ]
      }
    }
  });
  require(['form', 'upload', 'toastr'], function (Form, Upload, Toastr) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
      _bindevent.apply(this, [form]);
      try {
        require(['plantuml', 'viz', 'graphviz', 'mermaid', 'echarts', 'katex', 'vditor'], function (Plantuml, Viz, Graphviz, Mermaid, Echarts, Katex, Vditor) {
          // 解决require 模式下 数学公式渲染无效
          window.plantumlEncoder = Plantuml;
          window.Viz = Viz;
          window.graphviz = Graphviz;
          window.mermaid = Mermaid;
          window.echarts = Echarts;
          window.katex = Katex;
          window.Vditor = Vditor;
          window.vditorlist = {};
          var eles = $(Config.knowbase.classname || '.vditor_editor', form);
          var url = window.location.href;
          var upload_url = '';
          var linkToImgUrl = null;
          var pos = url.indexOf('.php');
          if (pos != -1) {
            linkToImgUrl = upload_url = url.substring(0, pos + 4) + '/knowbase/ajax/upload';
          }
          var toolbar = [
            "emoji",
            "headings",
            "bold",
            "italic",
            "strike",
            "link",
            "|",
            "list",
            "ordered-list",
            "check",
            "outdent",
            "indent",
            "|",
            "quote",
            "line",
            "code",
            "inline-code",
            "insert-before",
            "insert-after",
            "|",
            "upload",
            "record",
            "table",
            "|",
            "undo",
            "redo",
            "|",
            "fullscreen",
            "edit-mode",
            {
                name: "more",
                toolbar: [
                    "both",
                    "code-theme",
                    "content-theme",
                    "export",
                    "outline",
                    "preview",
                    "devtools",
                    "info",
                    "help",
                ],
            },
        ];
          if (show_history==1) {
            toolbar.push({
                  name: "page_history",
                  tip: '查看历史版本',
                  tipPosition: 'n',
                  className: 'page_history',
                  icon: '<svg xmlns="http://www.w3.org/2000/svg" height="40px" viewBox="0 -960 960 960" width="40px" fill="#5f6368"><path d="M478-120q-145.33 0-248.83-100.83-103.5-100.84-108.5-246.5H188q4.67 118 88.17 199.33 83.5 81.33 201.83 81.33 123.67 0 209.5-86.5t85.83-210.16q0-121.67-86.5-205.84-86.5-84.16-208.83-84.16-68.33 0-128 31.33t-102.67 84H354v66.67H134.67V-810h66.66v102q51.67-62 123.84-97 72.16-35 152.83-35 75 0 140.83 28.17 65.84 28.16 115 76.66Q783-686.67 811.5-621.5T840-481.33q0 75-28.5 140.83-28.5 65.83-77.67 114.67-49.16 48.83-115 77.33Q553-120 478-120Zm122.67-195.33-153.34-152V-682H514v187.33l134 132-47.33 47.34Z"/></svg>',
                  click () {},
            });
          }

          if (show_link==1) {
            toolbar.push({
              name: "page_link",
              tip: '前往前端查看该文档',
              tipPosition: 'n',
              className: 'page_link',
              icon: '<svg xmlns="http://www.w3.org/2000/svg" height="40px" viewBox="0 -960 960 960" width="40px" fill="#5f6368"><path d="M446.67-280H280q-83 0-141.5-58.5T80-480q0-83 58.5-141.5T280-680h166.67v66.67H280q-55.56 0-94.44 38.84-38.89 38.84-38.89 94.33 0 55.49 38.89 94.49 38.88 39 94.44 39h166.67V-280ZM323.33-446.67v-66.66h313.34v66.66H323.33Zm190 166.67v-66.67H680q55.56 0 94.44-38.84 38.89-38.84 38.89-94.33 0-55.49-38.89-94.49-38.88-39-94.44-39H513.33V-680H680q83 0 141.5 58.5T880-480q0 83-58.5 141.5T680-280H513.33Z"/></svg>',
              click () {
                window.openPageLink();
              },
            });
          }

          if (eles.length > 0) {
            // 只能用ID初始化 草
            for (var i = 0; i < eles.length; i++) {
              var ele = $(eles[i]);
              var id = ele.attr('id');
              if (id) {
                var content = $('#' + id.replace('-vditor', '')).val();
                params = {
                  'mode': mode,
                  'cache': {
                    enable: content.length == 0 && preview == 0 ? true : false
                  },
                  theme: editor_theme,
                  'cdn': '/assets/addons/knowbase',
                  'height': height,
                  'value': content,
                  outline: {enable: outline == 1 ? true : false},
                  toolbar: toolbar,
                  preview: {
                    theme: {current: content_theme},
                    hljs: {
                      enable: true,
                      style: code_theme,
                      lineNumber: code_show_number == 1 ? true : false
                    },
                    markdown: {
                      sanitize: true
                    },
                  },
                  upload: {
                    accept: 'image/*,.mp3, .wav, .rar, .zip,.mp4,.pdf,.xls,.xlsx,.doc,.docx,.ppt,.pptx',
                    max: upload_max_size,
                    token: false,
                    multiple: true,
                    extraData:{'vditor_id':id},
                    url: upload_url,
                    linkToImgUrl: linkToImgUrl,
                    linkToImgFormat:function (response){
                      var data = JSON.parse(response);
                      var url = data.data.fullurl;
                      var original = data.data.original;
                      var vData = {
                        msg: '',
                        code: 0,
                        data: {
                          originalURL: original,
                          url: url
                        }
                      };
                      return JSON.stringify(vData);
                    },
                    filename(name) {
                      return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '').replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '').replace('/\\s/g', '');
                    },
                    format(files, responseText) {
                      let data = JSON.parse(responseText);
                      //上传文件请求状态
                      if (data.code == 1) {
                        let succ = {};
                        for (let i = 0; i < data.data.length; i++) {
                          succ[data.data[i].filename] = data.data[i].fullurl;
                        }
                        //文件回显
                        return JSON.stringify({
                          data: data.msg,
                          code: 0,
                          data: {
                            errFiles: [],
                            succMap: succ
                          }
                        });
                      } else {
                        Toastr.error(data.msg);
                      }
                    },
                    handler: function(files) {
                      var that = this;
                      files.map((file) => {
                        Upload.api.send(file, function(data, ret, msg) {
                          var url =Fast.api.cdnurl(data.url,true);
                          if (file.type.match(/^image\//i)) {
                            window.vditorlist[that.extraData.vditor_id].insertValue("![](" +url + ")\n", true);
                          } else {
                            window.vditorlist[that.extraData.vditor_id].insertValue("[" +url + "](" +url + ")\n", true);
                          }
                        });
                      });
                    },
                  },
                  input: function (val) {
                    window.changeContent = true;
                    window.hasOldContent = false;
                    checkHtmlTags();
                  },
                  after: function () {
                    $('.vditor-reset').on('paste', function (event) {
                      editor_id = null;
                      var ele = $(this).parent();
                      while (ele.length > 0 && ele[0].tagName.toLowerCase() == 'div') {
                        if (ele.hasClass('vditor_editor')) {
                          editor_id = ele.attr('id');
                          break;
                        }
                        ele = ele.parent();
                      }
                      //防止预览模式下没有触发input异常
                      setTimeout(function (){
                        checkHtmlTags();
                      },500);
                      
                    });
                   
                  }
                };

                if (preview == 1) {


                  params['preview'] = {
                    mode: 'both',
                    markdown: {
                      toc: true,
                      sanitize: true
                    },
                    hljs: {
                      enable: true,
                      style: 'github',
                      lineNumber: true
                    },
                    parse: function (e) {

                    },
                  };

                }
                if (auto_upload_image_from_text==0) {
                   params['upload']['linkToImgUrl'] = null;
                   params['upload']['linkToImgFormat'] = null;
                }
                if (preview == 1) {
                  delete params['upload'];
                  params['speech'] = {enable: true};
                  window.vditorlist[id] = Vditor.preview(eles[i], content, params);
                  eles[i].addEventListener('click', function (event) {
                    if (event.target.tagName === 'IMG') {
                      Vditor.previewImage(event.target, 'zh_CN', 'classic');
                    }
                  });
                } else {
                  window.vditorlist[id] = new Vditor(id, params);
                }

              }
            }
          }
        });
      } catch (e) {

      }

    };
  });
}


// 过滤所有html标记 只保留纯文本
function stripHtmlTags(str) {
  // return str.replace(/<[^>]*>/g, '');
  return str.replace(/<[^>?]*[^?]>/g, '');
}

function checkHtmlTags() {
  if (editor_id != null && filter_tags==1) {
    // 没有被触发，主动触发一次
    var val = window.vditorlist[editor_id].getValue();
    var newVal = stripHtmlTags(val);
    if (newVal != val) {
      window.vditorlist[editor_id].setValue(newVal);
    }
  }
}

require.config({
    paths: {
        'summernote': '../addons/summernote/lang/summernote-zh-CN.min'
    },
    shim: {
        'summernote': ['../addons/summernote/js/summernote.min', 'css!../addons/summernote/css/summernote.min.css'],
    }
});
require(['form', 'upload'], function (Form, Upload) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        try {
            //绑定summernote事件
            if ($(Config.summernote.classname || '.editor', form).length > 0) {
                var selectUrl = typeof Config !== 'undefined' && Config.modulename === 'index' ? 'user/attachment' : 'general/attachment/select';
                require(['summernote'], function () {
                    var imageButton = function (context) {
                        var ui = $.summernote.ui;
                        var button = ui.button({
                            contents: '<i class="fa fa-file-image-o"/>',
                            tooltip: __('Choose'),
                            click: function () {
                                parent.Fast.api.open(selectUrl + "?element_id=&multiple=true&mimetype=image/", __('Choose'), {
                                    callback: function (data) {
                                        var urlArr = data.url.split(/\,/);
                                        $.each(urlArr, function () {
                                            var url = Fast.api.cdnurl(this, true);
                                            context.invoke('editor.insertImage', url);
                                        });
                                    }
                                });
                                return false;
                            }
                        });
                        return button.render();
                    };
                    var attachmentButton = function (context) {
                        var ui = $.summernote.ui;
                        var button = ui.button({
                            contents: '<i class="fa fa-file"/>',
                            tooltip: __('Choose'),
                            click: function () {
                                parent.Fast.api.open(selectUrl + "?element_id=&multiple=true&mimetype=*", __('Choose'), {
                                    callback: function (data) {
                                        var urlArr = data.url.split(/\,/);
                                        $.each(urlArr, function () {
                                            var url = Fast.api.cdnurl(this, true);
                                            var node = $("<a href='" + url + "'>" + url + "</a>");
                                            context.invoke('insertNode', node[0]);
                                        });
                                    }
                                });
                                return false;
                            }
                        });
                        return button.render();
                    };

                    $(Config.summernote.classname || '.editor', form).each(function () {
                        $(this).summernote($.extend(true, {}, {
                            height: isNaN(Config.summernote.height) ? null : parseInt(Config.summernote.height),
                            minHeight: parseInt(Config.summernote.minHeight || 250),
                            toolbar: Config.summernote.toolbar,
                            followingToolbar: parseInt(Config.summernote.followingToolbar),
                            placeholder: Config.summernote.placeholder || '',
                            airMode: parseInt(Config.summernote.airMode) || false,
                            lang: 'zh-CN',
                            fontNames: [
                                'Arial', 'Arial Black', 'Serif', 'Sans', 'Courier',
                                'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande',
                                "Open Sans", "Hiragino Sans GB", "Microsoft YaHei",
                                '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆',
                            ],
                            fontNamesIgnoreCheck: [
                                "Open Sans", "Microsoft YaHei",
                                '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆'
                            ],
                            buttons: {
                                image: imageButton,
                                attachment: attachmentButton,
                            },
                            dialogsInBody: true,
                            callbacks: {
                                onChange: function (contents) {
                                    $(this).val(contents);
                                    $(this).trigger('change');
                                },
                                onInit: function () {
                                },
                                onImageUpload: function (files) {
                                    var that = this;
                                    //依次上传图片
                                    for (var i = 0; i < files.length; i++) {
                                        Upload.api.send(files[i], function (data) {
                                            var url = Fast.api.cdnurl(data.url, true);
                                            $(that).summernote("insertImage", url, 'filename');
                                        });
                                    }
                                }
                            }
                        }, $(this).data("summernote-options") || {}));
                    });
                });
            }
        } catch (e) {

        }

    };
});

});